<template>
  <div class="main_content AddOrEditPersonal">
    <father-title :title="fatherTitle"></father-title>
    <div class="contentBox">
      <header-line :title="headerTitle"></header-line>
      <div class="form">
        <Form
            ref="form"
            :model="formValidate"
            :rules="ruleValidate"
            label-position="top"
            slot="content">
          <FormItem label="用户名" prop="username">
            <Input v-model="formValidate.username" placeholder="" />
          </FormItem>
          <FormItem label="登录账户" prop="loginAccount">
            <Input v-model="formValidate.loginAccount" placeholder="" />
          </FormItem>
          <FormItem v-if="!formValidate.userId" :rules="[{required: true, message: '登录密码不能为空', trigger: 'blur'}]" label="登录密码" prop="pw">
            <Input v-model="formValidate.pw" placeholder="" />
          </FormItem>
          <FormItem label="所属部门" prop="dept">
            <Cascader
                :data="deptList"
                v-model="formValidate.dept"
                change-on-select
                filterable
                placeholder="请选择部门"
                @on-change="changeDept"></Cascader>
          </FormItem>
          <FormItem label="手机号" prop="mobile">
            <Input v-model="formValidate.mobile" placeholder="" />
          </FormItem>
          <FormItem label="角色" prop="roleIdList">
            <span v-if="roleList.length === 0" style="color: #ed4014;"><Icon type="md-alert" /> 角色列表为空，请先选择部门，或为该部门添加角色</span>
            <CheckboxGroup v-model="formValidate.roleIdList">
              <Checkbox :label="item.roleId" v-for="item in roleList" :key="item.roleId">{{item.roleName}}</Checkbox>
            </CheckboxGroup>
          </FormItem>
          <FormItem label="邮箱" prop="email">
            <Input v-model="formValidate.email" placeholder="" />
          </FormItem>
          <FormItem label="状态" prop="status">
            <RadioGroup v-model="formValidate.status">
              <Radio :label="item.value" v-for="item in status" :key="item.value">{{item.key}}</Radio>
            </RadioGroup>
          </FormItem>
        </Form>
        <div>
          <Button :loading="loading" style="width: 80px;margin-top: 10px" type="primary" @click="addOrEditData">提交</Button>
          <Button style="width: 80px;margin-top: 10px; margin-left: 10px" @click="back">返回</Button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {formValidate, ruleValidate, status} from "./pageConfig";
import axios from "axios";
export default {
  name: 'AddOrEditPersonal',

  data() {
    return {
      status,
      formValidate: {...formValidate},
      ruleValidate: {...ruleValidate},
      roleList: [],// 角色列表
      deptList: [], // 部门列表
      fatherTitle: "",
      headerTitle: "",
      loading: false,
    };
  },

  mounted() {
    if(this.$route.params.type_id === 'add'){
      this.fatherTitle = "新增用户";
      this.headerTitle = "新增";
    }else{
      this.fatherTitle = "修改用户";
      this.headerTitle = "修改";
    }
    this.getAllList();
  },

  computed: {},

  methods: {
    // 获取角色信息
    getUserInfo(){
      this.$api.get('sp/sys/user/info/' + this.$route.params.type_id).then((res)=>{
        if(res.data.code === 0){
          this.formValidate = {...res.data.user};
          // 通过查找树遍历出节点路径
          this.formValidate.dept = this.$utils.util.findLeafPathInTree(this.deptList, this.formValidate.deptId, {
            value: "value",
            children: "children",
            compare: "deptId",
          });
          // 根据用户的所在部门获取角色列表
          this.getRoleList(res.data.user.deptId);
        }
      });
    },

    // 返回
    back(){
      this.$router.back();
    },

    // 新增或修改
    addOrEditData(){
      // 校验数据
      this.$refs.form.validate(state => {
        if (!state){
          return this.$Message.warning("请填写对应的值");
        }
        this.loading = true;
        // 判断新增或修改
        if(this.$route.params.type_id !== 'add'){

          this.$api.post('sp/sys/user/update', this.formValidate).then((res)=>{
            if(res.data.code === 0){
              this.$Message.success("修改成功");
              this.back();
            }
          }).finally(()=> this.loading = false);
        }else{
          // 用户密码加密
          this.formValidate.password = this.$utils.util.rsaEncrypt(this.formValidate.pw);
          this.$api.post('sp/sys/user/save', {...this.formValidate, pw: ''}).then((res)=>{
            if(res.data.code === 0){
              this.$Message.success("新增成功");
              this.back();
            }
          }).finally(()=> this.loading = false);
        }
      });
    },

    // 并发发起请求
    getAllList(){
      axios.all([this.getDeptList()]).then((axios.spread((dept)=>{
        if(dept.data.code === 0){
          // 组装级联数据
          this.deptList = this.$utils.util.convertCascaderList(dept.data.data, {
            value: 'deptId',
            label: 'name',
            children: 'children',
          });
        }
        // 判断是否为修改
        if(dept.data.code === 0 && this.$route.params.type_id !== 'add'){
          this.getUserInfo();
        }
      })));
    },

    // 获取角色列表
    getRoleList(deptId){
      return this.$api.get("sp/sys/role/selectByDeptId", {
        params: {
          deptId: deptId,
        }
      }).then((res)=>{
        if(res.data.code === 0){
          this.roleList = res.data.data;
        }
      });
    },

    // 获取部门列表
    getDeptList(){
      return this.$api.get('sp/sys/dept/list');
    },

    // 改变所属部门
    changeDept(value, selectValue){
      // 设置参数
      if(!this.$utils.util.isEqualsNull(selectValue)){
        this.formValidate.deptId = selectValue[selectValue.length -1].deptId;
        // 根据选择的部门获取角色列表
        this.getRoleList(this.formValidate.deptId);
        this.formValidate.deptName = selectValue[selectValue.length -1].name;
      }else{
        this.formValidate.deptId = null;
        this.formValidate.deptName = null;
      }
    },
  }
};
</script>

<style scoped lang="less">

.AddOrEditPersonal {
  .contentBox{
    overflow-y: scroll;
  }
  .form{
    display: flex;
    flex-direction: column;
    width: 800px;
    padding: 20px;
    flex: 1;
  }
}
</style>